using System;
using System.Collections.Generic;
using System.Text;

namespace MotionBlur.Butler.Triggers
{

    public class HourlyTrigger : ScheduledTrigger
    {

        private TimeSpan _StartAt;

        public TimeSpan StartAt
        {
            get { return _StartAt; }
            set { _StartAt = value; }
        }

        private double _RecurEvery;

        public double RecurEvery
        {
            get { return _RecurEvery; }
            set { _RecurEvery = value; }
        }

        internal override TimeSpan? GetSpanToNextOccurence(DateTime now)
        {

            DateTime startStamp = base.StartBy.Add(_StartAt);

            if (now < startStamp)
            {
                return startStamp.Subtract(now);
            }

            TimeSpan lifeSpan = now.Subtract(startStamp);
            TimeSpan deltaSpan = TimeSpan.FromHours(_RecurEvery);

            long passedOcurrences = lifeSpan.Ticks / deltaSpan.Ticks;

            long nextTicks = startStamp.Ticks + (passedOcurrences * deltaSpan.Ticks) + deltaSpan.Ticks;

            long ticksToNext = nextTicks - now.Ticks;

            DateTime nextStamp = now.AddTicks(ticksToNext);

            if (nextStamp > this.EndBy)
            {
                return null;
            }

            return TimeSpan.FromTicks(ticksToNext);

        }

    }

}
